package routers

import (
	"net/http"
	"time"

	_ "gitee.com/hlwqds/go-project/blogService/docs"
	"gitee.com/hlwqds/go-project/blogService/global"
	"gitee.com/hlwqds/go-project/blogService/internal/middleware"
	"gitee.com/hlwqds/go-project/blogService/internal/routers/api"
	v1 "gitee.com/hlwqds/go-project/blogService/internal/routers/api/v1"
	"gitee.com/hlwqds/go-project/blogService/pkg/limiter"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
)

func NewRouter() *gin.Engine {
	r := gin.New()
	r.Use(middleware.Recovery())
	r.Use(middleware.Tracing())
	r.Use(gin.Logger())
	r.Use(middleware.Translations())
	r.Use(middleware.AccessLog())
	l := limiter.NewMethodLimiter()
	for _, bucketSetting := range *global.BucketSettingSList {
		l.AddBucket(limiter.LimiterBucketRule{
			Key:          bucketSetting.Key,
			FillInterval: time.Second * bucketSetting.FillInterval,
			Capacity:     bucketSetting.Capacity,
			Quantum:      bucketSetting.Quantum,
		})
	}
	r.Use(middleware.RateLimiter(l))
	r.Use(middleware.ContextTimeout(global.ReqTimeOutSettingS.TimeOut * time.Second))
	tag := v1.NewTag()
	article := v1.NewArticle()
	upload := api.NewUpload()

	r.POST("/upload/file", upload.UploadFile)
	r.StaticFS("/static", http.Dir(global.AppSetting.UploadSavePath))
	r.GET("/auth", api.GetAuth)
	apiv1 := r.Group("/api/v1")
	{
		//对于apiv1组，注入JWT中间件进行校验
		apiv1.Use(middleware.JWT())
		apiv1.POST("/tags", tag.Create)
		apiv1.DELETE("/tags/:id", tag.Delete)
		apiv1.PUT("/tags/:id", tag.Update)
		apiv1.PATCH("/tags/:id/state", tag.Update)
		apiv1.GET("/tags", tag.List)

		apiv1.POST("/articles", article.Create)
		apiv1.DELETE("/articles/:id", article.Delete)
		apiv1.PUT("/articles/:id", article.Update)
		apiv1.PATCH("/articles/:id/state", article.Update)
		apiv1.GET("/articles", article.List)
		apiv1.GET("/articles/:id", article.Get)

	}
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	return r
}
